package org.meetunexpectedly.holder;

import org.meetunexpectedly.exception.BaseException;
import org.springframework.beans.factory.InitializingBean;

import javax.annotation.PreDestroy;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description: 用户上线信息 管理者(弃用)  在用户体量大时容易发生错误
 * @Author: pupil
 * @Date: 2024/08/21 下午 3:49
 */
@Deprecated
public class UserOnlineHolder implements InitializingBean {

    // 失效时间
    private static final long TIME_OUT = 1000 * 60 * 5;

    // 定时时间
    private static final long TIMED_TIME = 1000 * 60;

    // 时间单位(毫秒)
    private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;

    // 记录上线的用户
    private static ConcurrentHashMap<Long, Long> userOnlineMap = new ConcurrentHashMap<>();

    // 定时任务线程池
    private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    /**
     * 检测用户是否在线
     */
    private void checkUserOnline() {
        long currentTime = System.currentTimeMillis();
        userOnlineMap.forEach((userId, lastTime) -> {
            // 用户下线
            if (currentTime - lastTime > TIME_OUT) {
                userOnlineMap.remove(userId);
            }
        });

    }

    /**
     * 用户上线
     *
     * @param userId
     */
    public static void userOnline(Long userId) {
        if (userId == null) {
            throw new BaseException("用户id为空");
        }
        // 用户上线
        userOnlineMap.put(userId, System.currentTimeMillis());
    }


    /**
     * 获取在线用户
     *
     * @return
     */
    public static List<Long> getOnlineUsers() {
        List<Long> userIds = userOnlineMap.keySet().stream().collect(Collectors.toList());
        return userIds;
    }


    /**
     * 判断用户是否在线
     *
     * @param userId
     * @return
     */
    public static boolean isUserOnline(Long userId) {
        return userOnlineMap.containsKey(userId);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        scheduler.scheduleAtFixedRate(this::checkUserOnline, TIME_OUT, TIMED_TIME, TIME_UNIT);
    }

    // 确保在Spring容器关闭时关闭线程池
    @PreDestroy
    public void destroy() {
        scheduler.shutdown();
    }
}
